package com.geekgo.runningutil.util;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xwpf.converter.core.BasicURIResolver;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.util.Assert;
import org.springframework.util.Base64Utils;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.List;

/**
 * word转html工具类
 * @author geekgo
 * @version 2016/12/30 15:46
 */
public final class WordToHtmlUtil {

    /**
     *
     * @param wordPath
     * @param fileName 返回页面的名称
     * @param wordImagesPath
     * @param htmlPath
     * @return
     * @throws Exception
     */
    public static String word07ToHtml(String wordPath,String fileName,String wordImagesPath,String htmlPath) throws Exception {
        File filepath = new File(wordPath);
        if(!filepath.exists()&&!filepath .isDirectory()){
            filepath.mkdir();
        }
        File fileimagespath = new File(wordImagesPath);
        if(!fileimagespath.exists()&&!fileimagespath .isDirectory()){
            fileimagespath.mkdir();
        }
        File filehtmlpath = new File(htmlPath);
        if(!filehtmlpath.exists()&&!filehtmlpath .isDirectory()){
            filehtmlpath.mkdir();
        }
        if(!fileName.toLowerCase().endsWith(".docx")){
            throw new Exception("不支持的文件格式！");
        }
        File file = new File(wordPath+"/"+fileName);
        if(!file.exists()){
            throw new Exception("文件不存在！");
        }
        //load word into XWPFDocument
        InputStream inputStream = new FileInputStream(file);
        XWPFDocument document = new XWPFDocument(inputStream);

        //HTML 配置
        XHTMLOptions options = XHTMLOptions.create().indent(4);

        //配置网页中图片加载方式，即img的src属性 后面会自动追加/word/media路径
        //这里设置images，即:<img src="images/word/media/ + 图片名字"/>
        options.URIResolver(new BasicURIResolver("file/images"));

        //图片实际保存地址，即保存在服务器哪里
        FileImageExtractor extractor = new FileImageExtractor(new File(wordImagesPath));
        options.setExtractor(extractor);
        //构件文件输出流
        String fileNameStr = fileName.substring(0,fileName.indexOf("."));
        String htmlName = fileNameStr+".html";
        OutputStream outputStream = new FileOutputStream(new File(htmlPath+"/"+htmlName));

        //转化
        XHTMLConverter.getInstance().convert(document,outputStream,options);

        return htmlName;
    }

    /**
     * word转换成html字符串，直接返回给前端渲染
     * @param wordPath
     * @param fileName
     * @param wordImagesPath
     * @return
     * @throws Exception
     */
    /*public static String  getWord07HtmlContent(String wordPath,String fileName,String wordImagesPath)throws Exception{
        File filepath = new File(wordPath);
        if(!filepath.exists()&&!filepath .isDirectory()){
            filepath.mkdir();
        }
        File fileimagespath = new File(wordImagesPath);
        if(!fileimagespath.exists()&&!fileimagespath .isDirectory()){
            fileimagespath.mkdir();
        }
        if(!fileName.toLowerCase().endsWith(".docx")){
            throw new Exception("不支持的文件格式！");
        }
        File file = new File(wordPath+"/"+fileName);
        if(!file.exists()){
            throw new Exception("文件不存在！");
        }
        //load word into XWPFDocument
        InputStream inputStream = new FileInputStream(file);
        XWPFDocument document = new XWPFDocument(inputStream);

        //HTML 配置
        XHTMLOptions options = XHTMLOptions.create().indent(4);

        //配置网页中图片加载方式，即img的src属性 后面会自动追加/word/media路径
        //这里设置images，即:<img src="images/word/media/ + 图片名字"/>
        options.URIResolver(new BasicURIResolver("file/images"));

        //图片实际保存地址，即保存在服务器哪里
        FileImageExtractor extractor = new FileImageExtractor(new File(wordImagesPath));
        options.setExtractor(extractor);
        //构件文件输出流
        String fileNameStr = fileName.substring(0,fileName.indexOf("."));
        String htmlName = fileNameStr+".html";
        OutputStream outputStream = new FileOutputStream(new File(htmlPath+"/"+htmlName));

        //转化
        XHTMLConverter.getInstance().convert(document,outputStream,options);

        return htmlName;
    }*/

    /**
     * word 2003 转换成html
     * @param wordPath
     * @param fileName
     * @param wordImagesPath
     * @param htmlPath
     * @throws ParserConfigurationException
     * @throws IOException
     * @throws TransformerException
     * @throws Exception
     */
    public void word03ToHtml(String wordPath,String fileName,String wordImagesPath,String htmlPath)
            throws ParserConfigurationException,IOException,TransformerException,Exception {
        File filepath = new File(wordPath);
        if(!filepath.exists()&&!filepath .isDirectory()){
            filepath.mkdir();
        }
        File fileimagespath = new File(wordImagesPath);
        if(!fileimagespath.exists()&&!fileimagespath .isDirectory()){
            fileimagespath.mkdir();
        }
        File filehtmlpath = new File(htmlPath);
        if(!filehtmlpath.exists()&&!filehtmlpath .isDirectory()){
            filehtmlpath.mkdir();
        }
        if(!fileName.toLowerCase().endsWith(".doc")){
            throw new Exception("不支持的文件格式！");
        }
        File file = new File(wordPath+"/"+fileName);
        if(!file.exists()){
            throw new Exception("文件不存在！");
        }
        HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(wordPath+"/"+fileName));//WordToHtmlUtils.loadDoc(new FileInputStream(inputFile));
        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
                DocumentBuilderFactory.newInstance().newDocumentBuilder()
                        .newDocument());
        wordToHtmlConverter.setPicturesManager( new PicturesManager()
        {
            public String savePicture(byte[] content,
                                      PictureType pictureType, String suggestedName,
                                      float widthInches, float heightInches )
            {
                return "file/images/"+suggestedName;
            }
        } );
        wordToHtmlConverter.processDocument(wordDocument);
        //save pictures
        List pics=wordDocument.getPicturesTable().getAllPictures();
        if(pics!=null){
            for(int i=0;i<pics.size();i++){
                Picture pic = (Picture)pics.get(i);
                System.out.println();
                try {
                    pic.writeImageContent(new FileOutputStream(wordImagesPath + pic.suggestFullFileName()));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        Document htmlDocument = wordToHtmlConverter.getDocument();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(out);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.METHOD, "html");
        serializer.transform(domSource, streamResult);
        out.close();
        writeFile(new String(out.toByteArray(),"UTF-8"), htmlPath);
    }
    public static void writeFile(String content, String path) {
        FileOutputStream fos = null;
        BufferedWriter bw = null;
        try {
            File file = new File(path);
            fos = new FileOutputStream(file);
            bw = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"));
            bw.write(content);
        } catch (FileNotFoundException fnfe) {
            fnfe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                if (bw != null)
                    bw.close();
                if (fos != null)
                    fos.close();
            } catch (IOException ie) {
            }
        }
    }

    /**
     * word转换成html字符串，直接返回给前端渲染
     * @param wordPath
     * @param fileName
     * @return
     * @throws ParserConfigurationException
     * @throws IOException
     * @throws TransformerException
     * @throws Exception
     */
    public static String getWord03HtmlContent(String wordPath,String fileName)
            throws ParserConfigurationException,IOException,TransformerException,Exception{
        File filepath = new File(wordPath);
        if(!filepath.exists()&&!filepath .isDirectory()){
            filepath.mkdirs();
        }
        if(!fileName.toLowerCase().endsWith(".doc")){
            throw new Exception("不支持的文件格式！");
        }
        File file = new File(wordPath+"/"+fileName);
        if(!file.exists()){
            throw new Exception("文件不存在！");
        }
        HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(wordPath+"/"+fileName));
        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
                DocumentBuilderFactory.newInstance().newDocumentBuilder()
                        .newDocument());
        wordToHtmlConverter.setPicturesManager( new PicturesManager()
        {
            public String savePicture(byte[] content,
                                      PictureType pictureType, String suggestedName,
                                      float widthInches, float heightInches )
            {
                return "data:image/png;base64,"+Base64Utils.encodeToString(content);
            }
        } );
        wordToHtmlConverter.processDocument(wordDocument);
        Document htmlDocument = wordToHtmlConverter.getDocument();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(out);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.METHOD, "html");
        serializer.transform(domSource, streamResult);
        out.close();
        return out.toString("UTF-8");
    }
}
